﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models.ResponseModel;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Services.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Newtonsoft.Json.Linq;
using System.Text.Json.Nodes;
using RndMaterialDisposalService.Models.RequestModel;
using Microsoft.AspNetCore.Authorization;
using RndMaterialDisposalService.Models.Entitys;
using RndMaterialDisposalService.Repository;
using RndMaterialDisposalService.Services;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// 工作台
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class PortalCommonController : ControllerBase
    {
        private readonly ILogger<PortalCommonController> logger;
        private readonly IDataDictionaryService dictService;
        private readonly IPortalCommonService portalCommonService;
        private readonly IUserInfoService userInfoService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_dictService"></param>
        /// <param name="_IPortalCommonService"></param>
        public PortalCommonController(ILogger<PortalCommonController> _logger, IDataDictionaryService _dictService, IPortalCommonService _IPortalCommonService, IUserInfoService _IUserInfoService)
        {
            logger = _logger;
            dictService = _dictService;
            portalCommonService = _IPortalCommonService;
            userInfoService = _IUserInfoService;
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetTodoList")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> GetTodoList(string userId, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await portalCommonService.GetTodoList(userId, keyWord, sortField, SortDir, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<ToDoModel>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取待办列表(移动端),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 获取已办列表
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetDoneList")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> GetDoneList(string userId, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await portalCommonService.GetDoneList(userId, keyWord, sortField, SortDir, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<VToDoneDto>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取已办列表(移动端),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 获取待阅
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="keyWord"></param>
        /// <param name="sortField"></param>
        /// <param name="SortDir"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetToReadList")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> GetToReadList(string userId, string? keyWord, string? sortField = "ArrivalDate", string? SortDir = "desc", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var result = await portalCommonService.GetToReadList(userId, keyWord, sortField, SortDir, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<VToReadDto>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);
                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取待阅(移动端),用户ID：{userId},搜索：{keyWord},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 获取当前审批人
        /// </summary>
        /// <param name="procInstID"></param>
        /// <returns></returns>
        [HttpGet("GetWorkListItemUser")]
        public async Task<IActionResult> GetWorkListItemUserByProcInstID(int procInstID)
        {
            try
            {
                var result = await portalCommonService.GetWorkListItemUserByProcInstID(procInstID);
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取当前审批人(移动端),流程实例ID：{procInstID},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 获取流程实例
        /// </summary>
        /// <param name="procSetId"></param>
        /// <param name="folio"></param>
        /// <param name="originator"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("GetProcInst")]
        [PageList]
        public async Task<IActionResult> GetProcInst(int procSetId, string? folio, string? originator, DateTime? startDate, DateTime? endDate, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                if (string.IsNullOrEmpty(folio))
                {
                    folio = "";
                }
                if (string.IsNullOrEmpty(originator))
                {
                    originator = "";
                }
                if (startDate == null)
                {
                    var strStartDate = "1900-01-01 0:00:00";
                    startDate = DateTime.Parse(strStartDate);
                }
                if (endDate == null)
                {
                    var strEndDate = DateTime.Now.ToString("yyyy-MM-dd");
                    endDate = DateTime.Parse(strEndDate + " 23:59:59");
                }
                var result = await portalCommonService.GetProcInst(procSetId, folio, originator, startDate, endDate, pageIndex, pageSize);
                var totalCount = result.TotalCount;
                var userResult = ApiResponsePageList<ProcInst>.CreatePageListByResult(result.Data, pageIndex, pageSize, totalCount);

                //获取流程实例当前审批人
                var procInstIdList = userResult.Data.Select(a => a.ID.ToString()).ToList();
                var ApplicationDataList = await portalCommonService.GetBatchProcessInstance(procInstIdList);


                //填充发起人长工号/当前审批人
                var userInfo = userInfoService.GetUserInfoList("", 1, 10000000).Result;
                userResult.Data.ForEach((x) =>
                {
                    //var EmployeeInfo = userInfoService.GetUserInfo(x.TempName).Result;
                    if (userInfo.Data != null)
                    {
                        var EmployeeInfo = userInfo.Data.FirstOrDefault(a => a.UserId == x.TempName);
                        if (EmployeeInfo != null)
                        {
                            x.EmployeeNumber = EmployeeInfo.EmployeeNumber;
                        }

                        var ApplicationData = ApplicationDataList.FirstOrDefault(a => a.ProcInstId.Trim() == x.ID.ToString());
                        if (ApplicationData != null)
                        {
                            x.ApproveName = ApplicationData.CurrentHandler?.Trim();
                        }
                    }
                });

                return Ok(userResult);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"获取流程实例(移动端),procSetId：{procSetId},单号：{folio},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workItemReq"></param>
        /// <returns></returns>
        [HttpPost("GetEDPWorkItemList")]
        [PageList]
        public async Task<IActionResult> GetEDPWorkItemList(EDPWorkItemReq workItemReq)
        {
            var data = await portalCommonService.GetEDPWorkItemList(workItemReq.userId,  workItemReq.keyword ?? "", workItemReq.pageIndex ?? 1, workItemReq.pageSize ?? 10);
            var result = ApiResponsePageList<ToDoModel>.CreatePageListByResult(data.Data, workItemReq.pageIndex ?? 1, workItemReq.pageSize ?? 10, data.TotalCount);
            return Ok(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workItemReq"></param>
        /// <returns></returns>
        [HttpPost("GetEDPWorkDoneList")]
        [PageList]
        public async Task<IActionResult> GetEDPWorkDoneList(EDPWorkItemReq workItemReq)
        {
            var data = await portalCommonService.GetEDPWorkDoneList(workItemReq.userId, workItemReq.keyword ?? "", workItemReq.pageIndex ?? 1, workItemReq.pageSize ?? 10);
            var result = ApiResponsePageList<VToDoneDto>.CreatePageListByResult(data.Data, workItemReq.pageIndex ?? 1, workItemReq.pageSize ?? 10, data.TotalCount);
            return Ok(result);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="workItemReq"></param>
        /// <returns></returns>
        [HttpPost("GetEDPWorkReadList")]
        [PageList]
        public async Task<IActionResult> GetEDPWorkReadList(EDPWorkItemReq workItemReq)
        {
            var data = await portalCommonService.GetEDPWorkReadList(workItemReq.userId, workItemReq.keyword ?? "", workItemReq.pageIndex ?? 1, workItemReq.pageSize ?? 10);
            var result = ApiResponsePageList<VToReadDto>.CreatePageListByResult(data.Data, workItemReq.pageIndex ?? 1, workItemReq.pageSize ?? 10, data.TotalCount);
            return Ok(result);
        }

        /// <summary>
        /// 待办、待阅 数量
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet("GetTodoToReadCount")]
        [Authorize("policy1")]
        public async Task<IActionResult> GetTodoToReadCount(string userId)
        {
            try
            {
                var data = await portalCommonService.GetTodoToReadCount(userId);
                return Ok(new { TodoCount = data.todoCount, ToReadCount = data.toReadCount });
            }
            catch (Exception ex)
            {
                logger.LogInformation($"待办事项阅读数据量(移动端),用户ID：{userId},时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }

        /// <summary>
        /// 移动端发起流程列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("StartProcesslist")]
        [PageList]
        [Authorize("policy1")]
        public async Task<IActionResult> StartProcesslist(string? keyword, int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var data = await portalCommonService.MobileProcesslist();
                var rsp = data.Where(p => "1".Equals(p.Value));
                if (!string.IsNullOrEmpty(keyword))
                {
                    rsp = rsp.Where(p => p.Name!.Contains(keyword));
                }
                var result = ApiResponsePageList<StandardDictionaryConfigurationModel>.CreatePageList(rsp.ToList(), pageIndex, pageSize);
                return Ok(result);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"移动端发起流程列表,时间：{DateTime.Now},异常原因：{ex.ToString()}");
                throw;
            }
        }
    }
}
